package app.myproject.reader;

import java.net.URL;
import java.util.Iterator;
import java.util.UUID;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class ApplePageReader extends AbstractPageReader {
	
	public void read(String link) {
		try {
			write("{");
			write("\"page\":\"" + link + "\"");
			if (connect(link)) {
				
				write(",\"status\": \"available\"");
				
				String rnd = UUID.randomUUID().toString();
				URL url = new URL(link + "?p=" + rnd);
				Document doc = Jsoup.parse(url, 3000);
				
				Element page = doc.select("ul.all-models").first();
				if (page != null) {
					write(",\"items\": [");
					Iterator<Element> list = page.select("li").iterator();
					while (list.hasNext()) {
						Element item = list.next();
						write("{\"item\":\"");
						write(item.text());
						write("\"}");
						if (list.hasNext()) write(",");
					}
					write("]");
				} 
				else {
					write(",\"items\": []");
				}
			}
			else {
				write(",\"status\": \"currently unavailable\"");
			}
			write("}");
		}
		catch(Exception e) {
			System.err.println(e.getMessage());
		}
	}
	
}
